import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/banner_entity.dart';
import 'package:wanxiang_app/bean/deal_entity.dart';
import 'package:wanxiang_app/bean/game_list_entity.dart';
import 'package:wanxiang_app/bean/news_entity.dart';
import 'package:wanxiang_app/pages/home/black.dart';
import 'package:wanxiang_app/pages/home/buyResult.dart';
import 'package:wanxiang_app/pages/home/detail.dart';
import 'package:wanxiang_app/pages/home/hot.dart';
import 'package:wanxiang_app/pages/home/liveList.dart';
import 'package:wanxiang_app/pages/home/newsList.dart';
import 'package:wanxiang_app/pages/home/qa.dart';
import 'package:wanxiang_app/pages/home/safe.dart';
import 'package:wanxiang_app/pages/home/search.dart';
import 'package:wanxiang_app/pages/home/searchResult.dart';
import 'package:wanxiang_app/pages/home/service.dart';
import 'package:wanxiang_app/pages/home/tousu.dart';
import 'package:wanxiang_app/pages/my/priceMy.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:marquee_widget/marquee_widget.dart';
import 'package:get/get.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';

import '../../bean/anchor_entity.dart';
import '../../bean/goods_list_entity.dart';
import '../../utils/common.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/tabChangeEvent.dart';
import '../../utils/toast_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../widgets/simple_dialog.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';

import '../login/login.dart';
import '../login/login_code.dart';
import '../msg/notice.dart';
import 'newsDetaill.dart';


class HomeController extends GetxController{
  int aa = 0;
  void increment(){
    aa ++ ;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    _initAllData();
  }

  void _initAllData(){
    newsType = [];
    Map map1 = {"id":'0',"name":'全部'};
    newsType.add(map1);

    Map map2 = {"id":'1',"name":'手游攻略'};
    newsType.add(map2);

    Map map3 = {"id":'2',"name":'端游攻略'};
    newsType.add(map3);

    Map map4 = {"id":'3',"name":'行业资讯'};
    newsType.add(map4);
    _getBannerData();
    _getGameListData();
    _getDealListData();
    _getAnchorListData();
    _getNews('0');
  }

   List<BannerData> bannerData = [];
   List<GameListData> gameListData = [];
   List<DealData> dealList = [];
   List<AnchorData> anchorList = [];
   List<GoodsListData> goodsList = [];
   List<NewsData> newsList = [];
    List<Map> newsType = [];
  void _getBannerData(){
    Map map= {
      "banner_type":'banner_app',
    };
    DioManager.getInstance().post(ServiceUrl.banner, map, (data) async {
      BannerEntity bannerEntity = BannerEntity.fromJson(jsonDecode(data));
       bannerData = bannerEntity.data;
       update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getGameListData(){
    Map map= {
      "top":'10',
    };
    DioManager.getInstance().post(ServiceUrl.gameList, map, (data) async {
      GameListEntity bannerEntity = GameListEntity.fromJson(jsonDecode(data));
      gameListData = bannerEntity.data;
      _getGoodslListData(gameListData[clickGameIndex].code);

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }


  void _getDealListData(){
    DioManager.getInstance().post(ServiceUrl.dealList, null, (data) async {
      DealEntity bannerEntity = DealEntity.fromJson(jsonDecode(data));
      dealList = bannerEntity.data;
      _startTimer();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getAnchorListData(){
    DioManager.getInstance().post(ServiceUrl.anchorList, null, (data) async {
      AnchorEntity bannerEntity = AnchorEntity.fromJson(jsonDecode(data));
      anchorList = bannerEntity.data;
      // liveAnim();
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getGoodslListData(name){
    DioManager.getInstance().post(ServiceUrl.goodsList, {
      'channel_name':name,
      'top':'3',
    }, (data) async {
      GoodsListEntity bannerEntity = GoodsListEntity.fromJson(jsonDecode(data));
      goodsList = bannerEntity.data;
      if(_hotTimer==null){
        // hotAnim();
      }

      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _getNews(id){
    DioManager.getInstance().post(ServiceUrl.news, {
      'top':'3',
      'type':id,
      'pagesize':"3",
      'page':"1",
    }, (data) async {
      NewsEntity bannerEntity = NewsEntity.fromJson(jsonDecode(data));
      newsList = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

  int countValue = -1;
  late Timer _timer;
  void _startTimer() {
    const Duration duration = Duration(seconds: 2);
    _timer = Timer.periodic(duration, (timer) {
      if (countValue >= dealList.length-1) {
        countValue=0;
      }else{
        countValue = countValue +1;
      }
      update();

    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
    }
  }
  int clickGameIndex = 0;
  int clickNewsIndex = 0;
  changeGame(){
    _getGoodslListData(gameListData[clickGameIndex].code);
    update();
  }
  changeNews(){
    _getNews(newsType[clickNewsIndex]['id']);
    update();
  }
  late BuildContext mContext ;
  showLive(url){
    showDialog(context: mContext, builder: (BuildContext context1) {
      return MySimpleDialog(callBack: (String content) {
        if(content == 'cancel'){
          Navigator.pop(context1);
        }else if(content == 'sure'){
          launchUrl(Uri.parse((url)));
          Navigator.pop(context1);
        }
      },
        msg: "查看主播详情将跳转至第三方网站",
        sureText: "确定",
      );
    });
  }

  final ItemScrollController itemScrollController = ItemScrollController();
  final ScrollOffsetController scrollOffsetController = ScrollOffsetController();
  final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
  final ScrollOffsetListener scrollOffsetListener = ScrollOffsetListener.create();

  ScrollController hotScrollController = ScrollController();

  Timer? _hotTimer;
  hotAnim(){
    _hotTimer = Timer.periodic(const Duration(milliseconds: 3000), (timer) {
      clickGameIndex++;
      if(clickGameIndex==gameListData.length){
        clickGameIndex=0;
        itemScrollController.jumpTo(index: clickGameIndex);
      }
      // observerController?.jumpTo(index: clickGameIndex);
      if(clickGameIndex!=0){
        scrollOffsetController.animateScroll(offset: 80, duration: Duration(milliseconds: 3000));
      }
      changeGame();
    });
  }

  Timer? _liveTimer;

  int liveIndex = 0;
  final ItemScrollController liveItemScrollController = ItemScrollController();
  final ScrollOffsetController liveScrollOffsetController = ScrollOffsetController();
  final ItemPositionsListener liveItemPositionsListener = ItemPositionsListener.create();
  final ScrollOffsetListener liveScrollOffsetListener = ScrollOffsetListener.create();

  liveAnim(){
    _liveTimer = Timer.periodic( Duration(milliseconds: (1500*anchorList.length)), (timer) {
        liveItemScrollController.jumpTo(index: 0);
        Future.delayed(Duration(seconds: 1),(){
          liveScrollOffsetController.animateScroll(offset: (142.0*anchorList.length), duration: Duration(milliseconds: 1500*anchorList.length-1000));
        });
    });
  }


}

class HomePage extends GetView<HomeController> {

  late HomeController controller ;
  late BuildContext context ;

  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<HomeController>(() => HomeController());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<HomeController>(
      builder: (_){
        SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);

        return  Scaffold(
          extendBodyBehindAppBar: true,
          body: SingleChildScrollView(
            child: _content(),
          ),
        );
      },
    )
     ;
  }
  
  Widget _content(){
    return Container(
      child: Column(
        children: [
          _top(),

          // _tip(),
          _notice(),
          SizedBox(height: 15.h,),
          _hot('热门游戏','更多>>','hot_game.png'),
          SizedBox(height: 10.h,),
          _hotList(),
          _line(),
          _hot('合作主播','更多>>','live_anchor.png'),
          SizedBox(height: 3.h,),
          _liveList(),
          SizedBox(height: 5.h,),
          _line(),
          _hot('最新上架','更多>>','new_up.png'),
          SizedBox(height: 3.h,),
          _gameNamesList(),
            Column(
              children: _gameListItems(),
            ),
          SizedBox(height: 5.h,),
          _line(),
          _hot('游戏资讯','更多>>','home_news.png'),
          SizedBox(height: 3.h,),
          _typeList(),
          Column(
            children: _newsInfoItems(),
          ),
          SizedBox(height: 20.h,),
        ],
      ),
    );
  }

  Widget _top(){
    return  Column(
        children: [
          _topSearch(),
          _swiper(),
          _four(),
        ],
    ) ;
  }


  Widget _topSearch(){
    return  Container(
      padding: EdgeInsets.only(top:  MediaQueryData.fromWindow(window).padding.top+5.h,),
        height: 78.h,
        decoration: const BoxDecoration(
            gradient: LinearGradient(      //渐变位置
                begin: Alignment.topCenter, //右上
                end: Alignment.bottomCenter, //左下
                stops: [0.0, 1.0],         //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: [Color.fromRGBO(0, 123, 229, 1), Color.fromRGBO(101, 184, 255, 1)]
            )
        ),

        child: Container(
            margin: EdgeInsets.only(left: 16.w,right: 25.w),
            height: 32.h,
            alignment: Alignment.topCenter,
            child:
            Row(
              children: [
                Image.asset('assets/images/logo_new.png',width: 42.w,height: 52.h,),
                SizedBox(width: 17.w,),

                Expanded(
                    flex: 1,
                    child: InkWell(
                      onTap: (){
                        Get.to(()=>SearchPage(),preventDuplicates:false);
                      },
                      child:  Container(
                        height: 32.h,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(17.r)
                        ),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SizedBox(width: 18.w,),
                            Image.asset('assets/images/home_search.png',width: 13.w,height: 13.h,),
                            SizedBox(width: 8.w,),
                            Text('请输入游戏名称',style: TextStyle(
                                color: Color(0xFF8B8B8B),
                                fontSize: 13.sp
                            ),)
                          ],
                        ),
                      )
                    )),
                SizedBox(width: 21.w,),
                InkWell(
                  onTap: (){
                   bool islogin= Common.checkLogin();
                   if(islogin){
                     tabbarEventBus.fire(TabChangedEvent(400));
                   }else{
                     ToastUtil.show("请先登录");
                     Get.to(()=>LoginCodePage(),preventDuplicates:false);
                   }

                  },
                  child: Image.asset('assets/images/home_service_white.png',width: 24.w,height: 22.h,)
                ),
              ],
            )
        )
    );
  }

  Widget _four(){
    return Container(
      margin: EdgeInsets.only(top: 1.h,left: 8.w,right: 8.w),
      padding: EdgeInsets.fromLTRB(8.w, 18.h, 8.w, 9.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(topLeft: Radius.circular(10.r),topRight: Radius.circular(10.r)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _fourItem('极速回收','home_huishou.png',Color(0xFFCD7CFE)),
          _fourItem('中介担保','home_danbao.png',Color(0xFFCD7CFE)),
          _fourItem('安全保障','home_baozhang.png',Color(0xFFFC6B7A)),
          _fourItem('帮助中心','home_bangzhu.png',Color(0xFFFB9E36)),

          _fourItem('黑号查询','home_hei.png',Color(0xFFFB9E36)),
        ],
      ),
    );
  }

  Widget _fourItem(text,img,color){
    return InkWell(
      onTap: (){
        if(text=='中介担保'){
          Get.to(()=>ServicePage(),preventDuplicates:false);
        }else   if(text=='黑号查询'){
          Get.to(()=>BlackPage(),preventDuplicates:false);
        }else   if(text=='帮助中心'){
          Get.to(()=>QAPage(),arguments: '帮助中心',preventDuplicates:false);
        }else   if(text=='安全保障'){
          Get.to(()=>SafePage(),preventDuplicates:false);
        }else   if(text=='极速回收'){
          Constant.tabFirst = false;
          tabbarEventBus.fire(TabChangedEvent(500));
        }
      },
      child: Container(
        height: 75.h,
        width: 60.w,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10.r),
            boxShadow:const [
              BoxShadow(
                  color: Color(0x29007BE5),
                  offset: Offset(1, 1),
                  blurRadius:1,
                  spreadRadius:0.5
              ),
            ]
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 42.w,
              height: 42.w,
              child: Image.asset(Constant.IMG_BASE+img,width: 42.w,height: 42.w,),
            ),
            SizedBox(height: 5.h,),
            Text(text,style: TextStyle(
                color: Color(0xFF000000),
                fontSize: 13.sp
            ),)
          ],
        ),
      )
    ) ;
  }

  Widget _swiper(){
    return Container(
      margin: EdgeInsets.only(left: 14.w,right: 16.w,top: 3.h),
      height: 120.h,
      width: 328.w,

      child: ClipRRect(
        borderRadius: BorderRadius.circular(6.r),
    child: Swiper(
      itemBuilder: (context, index) {
        return CachedNetworkImage(imageUrl: controller.bannerData[index].url, imageBuilder: (context, imageProvider) => Container(
            height: 103.h,
            width: 328.w,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: imageProvider,
                fit: BoxFit.fill,
              ),
            )));
      },
      autoplay: true,
      itemCount: controller.bannerData.length,
      pagination: SwiperPagination(
          builder: SwiperCustomPagination(
              builder: (BuildContext context, SwiperPluginConfig config) {
                return NLIndicator(config.activeIndex, controller.bannerData.length);
              })),
    ),
      ),
      ) ;
  }

  Widget _tip(){
    return Container(
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 5.h),
      child: Row(
        children: [
          InkWell(
            onTap: (){
              Get.to(()=>ServicePage(),preventDuplicates:false);
            },
            child:  Container(
              width: 100.w,height: 130.h,
              decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/index_tip_1.png'),
                    fit: BoxFit.fill,
                  )
              ),
            )
          )
        ,
          SizedBox(width: 6.w,),
          Column(
            children: [
              Row(
                children: [
                  InkWell(
                      onTap: (){
                        Get.to(()=>BlackPage(),preventDuplicates:false);
                      },
                    child:   Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_2.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                ,
                  SizedBox(width: 6.w,),
                  InkWell(
                    onTap: (){
                      // ToastUtil.show('暂未开通');
                      Get.to(()=>PriceMyPage(),preventDuplicates:false);
                    },
                    child:    Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_3.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
               ,
                ],
              ),


              SizedBox(height: 6.h,),
              Row(
                children: [
                  InkWell(
                    onTap: (){
                      Get.to(()=>TousuPage(),preventDuplicates:false);
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_4.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                  ,

                  SizedBox(width: 6.w,),

                  InkWell(
                    onTap: (){
                      Get.to(()=>QAPage(),arguments: '常见问题',preventDuplicates:false);
                    },
                    child:  Container(
                      padding: EdgeInsets.only(left: 12.w),
                      width: 108.w,height: 60.h,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/index_tip_5.png'),
                            fit: BoxFit.fill,
                          )
                      ),
                    )
                  )
                 ,

                ],
              )
            ],
          )
        ],
      ),
    );
  }

  Widget _notice(){
    return Container(
      height: 35.h,
      width: 328.w,
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 4.h),
      padding: EdgeInsets.fromLTRB(14.w, 0, 13.w, 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.r),
          boxShadow:const [
      BoxShadow(
      color: Color(0x29007BE5),
        offset: Offset(1, 1),
        blurRadius:1,
        spreadRadius:0.5
    ),
    ]
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(Constant.IMG_BASE+'index_notice.png',width: 16.w,height: 14.h,),
          SizedBox(width: 11.w,),
          controller.countValue!=-1?
          Container(
            alignment: Alignment.center,
              height: 41.h,
            width: 266.w,
            child: Marquee(
              direction: Axis.vertical,
              animationDuration: const Duration(seconds: 1),
              directionMarguee: DirectionMarguee.oneDirection,
              child: Text(controller.dealList[controller.countValue].title,
                overflow: TextOverflow.ellipsis,
                softWrap: true,
                textAlign: TextAlign.left,
                style: TextStyle(fontSize: 12.sp),) ,
            )
          ):Container(),

        ],
      ),
    );
  }

  Widget _hot(leftText,rightText,leftImg){
    return Container(
      margin: EdgeInsets.only(left: 17.w,right: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Image.asset(Constant.IMG_BASE+'item_new.png',width: 22.w,height: 18.h,),
              SizedBox(width: 5.w,),
              Image.asset(Constant.IMG_BASE+leftImg,width: 64.w,height: 17.h,),
            ],
          ),
          
          InkWell(
            onTap: (){
              if(leftText =='合作主播'){
                Get.to(()=>LivePage(),preventDuplicates:false);
              }else if(leftText =='游戏资讯'){
                Get.to(()=>NewsListPage(),preventDuplicates:false);
              }else{
                Constant.clcikSellTab = false;
                Get.to(()=>HotPage('index'),arguments: {"type":1},preventDuplicates:false);
              }

            },
            child: Text(rightText,style: TextStyle(color:const Color(0xFF666666),fontSize: 13.sp ),),
          )

        ],
      ),
    );
  }


  Widget _hotList(){
    return
      Container(
        width: 328.w,
        height: 145.h,
        child: GridView.count(
          padding: EdgeInsets.all(0),
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: 5,
          mainAxisSpacing: 7.w,
          crossAxisSpacing: 18.h,
          childAspectRatio: 0.69 / 1,
          children: controller.gameListData.map((item) => _hotItem(item)).toList(),
        )
      );
  }

  Widget _hotItem(GameListData item){
    return InkWell(
      onTap: (){
        Get.to(()=>BuyResultPage(),
            preventDuplicates:false,
            arguments: {
          'channel_name':item.code,
          'channel_id':item.id,
          'keyword':'',
          'name':item.name
        });
      },
      child: Column(
        children: [
          Container(
            width: 54.w,
            height: 54.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
            ),
            alignment: Alignment.center,
            child:
            CachedNetworkImage(imageUrl: item.backimg, imageBuilder: (context, imageProvider) => Container(
                width: 54.w,
                height: 54.w,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: imageProvider,
                  ),
                )))
            ,
          ),
          Text(item.name,style: TextStyle(
            fontSize: 11.sp,color: Color(0xFF333333),
            overflow: TextOverflow.ellipsis
          ),)
        ],
      ) 
    ) ;
  }

  Widget _line(){
    return Container(
      margin: EdgeInsets.only(left: 16.w,right: 16.w,top: 10.h,bottom: 10.h),
      height: 1.h,
      decoration: BoxDecoration(
        color: Color(0xFFF5F5F5),
        // color: Color(0xFFFF0000),
      ),

    );
  }

  Widget _liveList(){
    return
      Container(
        margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 0),
        child: SingleChildScrollView(
          scrollDirection:Axis.horizontal,
          child: Row(
            children: _liveListItems(),
          ),
        )
      )
      ;
  }


  
  List<Widget> _liveListItems(){
    List<Widget> items = [];

    controller.anchorList.forEach((element) {
      items.add(_liveItem(element));
    });
   
    return items;
  }

  Widget _liveItem(AnchorData item){
    return InkWell(
      onTap: (){
        controller.showLive(item.openUrl);
      },
      child: Container(
        width: 142.w,
        height: 88.w,
        margin: EdgeInsets.only(right: 10.w),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10.r),
          child: CachedNetworkImage(imageUrl: item.imgUrl, imageBuilder: (context, imageProvider) => Container(
              width: 142.w,
              height: 88.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              )))
        ,
        ),
      )
    ) ;
  }


  Widget _gameNamesList(){
    return
      Container(
          margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 0),
          child: SingleChildScrollView(
            scrollDirection:Axis.horizontal,
            child: Row(
              children: _gameNameListItems(),
            ),
          )
      )
    ;

  }



  List<Widget> _gameNameListItems(){
    List<Widget> items = [];

    for(int i = 0;i<controller.gameListData.length;i++){
      items.add(_gameNameItems(controller.gameListData[i],i));
    }

    return items;
  }


  Widget _gameNameItems(element,index){

    return InkWell(
      onTap: (){
        controller.clickGameIndex = index;
        controller.changeGame();
      },
      child:  index == controller.clickGameIndex?_clickTag(element.name):
      _clickTagNo(element.name)
    );
  }

  Widget _typeList(){
    return controller.newsType.isEmpty?Container():
      Container(
          margin: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 0),
          child: SingleChildScrollView(
            scrollDirection:Axis.horizontal,
            child: Row(
              children: _newsTypeItems(),
            ),
          )
      )
    ;
  }

  List<Widget> _newsTypeItems(){
    List<Widget> items = [];

    for(int i = 0;i<controller.newsType.length;i++){
      items.add(_newsTypeItem(controller.newsType[i],i));
    }

    return items;
  }

  Widget _newsTypeItem(element,index){
    return InkWell(
        onTap: (){
          controller.clickNewsIndex = index;
          controller.changeNews();
        },
        child:  index == controller.clickNewsIndex?_clickTag(element['name']):
        _clickTagNo(element['name'])
    );
  }

  List<Widget> _newsInfoItems(){
    List<Widget> items = [];

    for(int i = 0;i<controller.newsList.length;i++){
      items.add(_newsInfoItem(controller.newsList[i]));
    }

    return items;
  }

  Widget _newsInfoItem(NewsData item){
    return InkWell(
        onTap: (){
          Get.to(()=>NewsDetailPage(),arguments: {
            "id":item.id.toString(),
          },preventDuplicates:false);
        },
        child:  Container(
          margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 10.h),
          child: Row(
            children: [
              Container(
                  width: 120.w,
                  height: 110.w,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12.r),
                    child:Stack(
                      children: [
                        Image.network(item.imgUrl,fit:BoxFit.cover,
                          width: 120.w,
                          height: 110.w,

                        ),
                      ],
                    ),
                  )
              ),
              SizedBox(width: 14.w,),
              Container(
                  width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w - 20.w,
                  child:  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item.title,
                        style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,),
                      SizedBox(height: 10.h,),

                      Text(item.introduce,
                        style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),maxLines: 2,    textAlign: TextAlign.left,
                        overflow: TextOverflow.ellipsis,),

                      SizedBox(height: 6.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(Common.transferDate(item.updateTime) ,
                            style: TextStyle(color: Color(0xFF999999),fontSize: 13.sp)),
                          Row(
                            children: [
                              Image.asset(Constant.IMG_BASE+'eye_open.png',width: 16.w,height: 10.h,),
                              SizedBox(width: 5.w,),
                              Text(item.lookNum.toString(),
                                  style: TextStyle(color: Color(0xFF999999),fontSize: 13.sp)),
                            ],
                          )
                        ],
                      )
                    ],
                  )
              )

            ],
          ),
        )
    );
  }


  Widget _clickTag(name){
    return  Container(
      alignment: Alignment.center,
      height: 30.h,
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
      margin: EdgeInsets.only(right: 10.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.r),
          color: const Color(0xFF007BE5)
      ),
      child: Text(name,style: TextStyle(color: Colors.white,fontSize: 14.sp),),
    );
  }
  Widget _clickTagNo(name){
    return  Container(
      alignment: Alignment.center,
      height: 30.h,
      padding: EdgeInsets.fromLTRB(12.w, 0, 12.w, 0),
      margin: EdgeInsets.only(right: 10.w),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.r),
          color: const Color(0xFFEDEEEF),
      ),
      child: Text(name,style: TextStyle(color: const Color(0xFF333333),fontSize: 14.sp),),

    );
  }

  List<Widget> _gameListItems(){
    List<Widget> items = [];
    for (var element in controller.goodsList) {
      items.add(_gameItems(element));
    }
    return items;
  }

  Widget _gameItems(GoodsListData item){
    return InkWell(
      onTap: (){
        Get.to(()=>DetailPage(),arguments: {
          "title":item.title,
          "record_id":item.channelId,
          "channel_name":item.channelName,
          "goods_id":item.id.toString(),
        },preventDuplicates:false);
      },
      child:  Container(
        margin: EdgeInsets.only(left: 16.w,right: 13.w,top: 10.h),
        child: Row(
          children: [
            Container(
                width: 120.w,
                height: 100.w,
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child:Stack(
                    children: [
                      Image.network(item.imgUrl,fit:BoxFit.cover,
                        width: 120.w,
                        height: 100.w,

                      ),
                      _officer(item),

                    ],
                  ),
                )
            ),
            SizedBox(width: 14.w,),
            Container(
                width: MediaQuery.of(context).size.width - 29.w - 14.w - 100.w - 20.w,
                child:  Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(item.title,
                      style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),maxLines: 2,    textAlign: TextAlign.left,
                      overflow: TextOverflow.ellipsis,),
                    SizedBox(height: 10.h,),
                    Text('区服：${item.categoryText}',style: TextStyle(color: Color(0xFF666666),fontSize: 13.sp),),
                    SizedBox(height: 6.h,),
                    Row(
                      children: [
                        Text('售价：',style: TextStyle(color: Color(0xFF666666),fontSize: 12.sp),),
                        Text('¥',style: TextStyle(color: Color(0xFFFF0000),fontSize: 12.sp),),
                        Text(item.sellPrice,style: TextStyle(color: Color(0xFFFF0000),fontSize: 18.sp),),
                      ],
                    )
                  ],
                )
            )

          ],
        ),
      )
    );
  }

  Widget _officer(GoodsListData item) {
    if(item.isDeductible=='1'){
      return InkWell(
          onTap: (){
            showDialog(context: context, builder: (BuildContext context1) {
              return MySimpleDialog(callBack: (String content) {
                if(content == 'cancel'){
                  Navigator.pop(context1);
                }else if(content == 'sure'){
                  Navigator.pop(context1);
                }
              },
                msg: item.baopei,
                sureText: "确定",
              );
            });
          },
          child: Container(
            child: Image.asset(Constant.IMG_BASE+'qianyue.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
          )
      );
    }

    return item.isSelf==0? InkWell(
        onTap: (){
          showDialog(context: context, builder: (BuildContext context1) {
            return MySimpleDialog(callBack: (String content) {
              if(content == 'cancel'){
                Navigator.pop(context1);
              }else if(content == 'sure'){
                Navigator.pop(context1);
              }
            },
              msg: item.baopei,
              sureText: "确定",
            );
          });
        },
        child: Container(
          child: Image.asset(Constant.IMG_BASE+'baopei.png',width: 52.w,height: 17.h,fit: BoxFit.fitWidth,),
        )
    ) :Container();
  }

}


class NLIndicator extends StatelessWidget {
  var _currentIndex;
  var _count;
  NLIndicator(this._currentIndex, this._count);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 150.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: List.generate(_count, (index){
          return _currentIndex == index ? Container(
            width: 24.w,
            height: 5.h,
            margin: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4)
            ),
          ) : Container(
            width: 8.w,
            height: 8.h,
            margin: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(20)
            ),
          );
        }),
      ),
    );
  }
}

